/* serverMain.c */

#include "server.h"

#include <time.h>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>

/* Enables debug and sets the -v command-line argument */
/* #define DEBUG */

/*! The wrapper function for the TCP server.  It is designed to be called as a daemon, but can also be called
    from the command line for debugging purposes with the -v argument. */
int main (int argc, char** argv)
{
#ifndef DEBUG
  int i;
  FILE *logFileTarget = NULL;
  FILE *debugTarget = NULL;
  char* optionDescription0 =
  "  Options:                                                                             \n"
  "    -h            = Help:                                                              \n"
  "                      Print usage information                                          \n"
  "                                                                                       \n";
  /* split for ANSI maximum string length of 509 */
  char* optionDescription1 =
  "    -l filename   = Error log file:                                                    \n"
  "                      Set log file to write errors to.  Normally this defaults to      \n"
  "                      FILE* ErrorServerOutput unless redirected, but this sets         \n"
  "                      ErrorServerOutput = Log file name.                               \n"
  "                                                                                       \n";
  /* split for ANSI maximum string length of 509 */
  char* optionDescription2 =
  "    -v [filename] = Verbose mode:                                                      \n"
  "                      Dump all transactions and errors to stdout / stderr,             \n"
  "                      or \"filename\" if provided.                                     \n";
#endif

  unsigned int verbose = 0;
  FILE* verboseServerOutput;
  FILE* errorServerOutput;
  
  time_t timer;
  struct tm *tblock;
  int retCode;


  /* set the default verbose and error targets */
  errorServerOutput = stderr;
  verboseServerOutput = stdout;

#ifndef DEBUG
  /**************************************************************************************/
  /* parse the command-line arguments                                                   */
  /**************************************************************************************/
  i = 1;
  while (i < argc)
  {
    if (strcmp ("-h", argv[i]) == 0)
    {
      /* print usage */
      fprintf (stderr, "Usage %s [option]\n", argv[0]);
      fprintf (stderr, "%s%s%s\n", optionDescription0, optionDescription1, optionDescription2);
      return 0;
    }
    else if (strcmp ("-l", argv[i]) == 0)
    {
      /* set logfile name */
      if (++i >= argc)
      {
        fprintf (stderr, "Expecting a filename to be provided after -l flag!\n");
        fprintf (stderr, "Usage %s [option]\n", argv[0]);
        fprintf (stderr, "%s%s%s\n", optionDescription0, optionDescription1, optionDescription2);
        exit (EXIT_FAILURE);
      }

      if (!(logFileTarget = fopen (argv[i], "a")))
      {
        fprintf (stderr, "Unable to open log file %s for appending: %s\n", argv[i], strerror (errno));
        exit (EXIT_FAILURE);
      }
      errorServerOutput = logFileTarget;

      /* mark the time in the server log */
      timer = time (NULL);
      tblock = localtime (&timer);
      fprintf (errorServerOutput, "%s Start: %s\n", argv[0], asctime (tblock));
      i++;
    }
    else if (strcmp ("-v", argv[i]) == 0)
    {
      /* verbose mode */
      verbose = 1;

      /* check if a debug target file was supplied */
      if (i < argc - 1) /* we still have more command-line arguments */
      {
        if (argv[i+1][0] != '-')
        {
          /* a filename was provided */
          if (!(debugTarget = fopen (argv[++i], "w")))
          {
            fprintf (stderr, "Unable to open debug target file %s : %s\n", argv[i], strerror (errno));
            exit (EXIT_FAILURE);
          }
          /* set this as the verbose and error target */
          errorServerOutput = debugTarget;
          verboseServerOutput = debugTarget;
        }
      }
      i++;
    }
    else
    {
      fprintf (stderr, "Unknown command line argument %s!\n", argv[i]);
      fprintf (stderr, "Usage %s [option]\n", argv[0]);
      fprintf (stderr, "%s%s%s\n", optionDescription0, optionDescription1, optionDescription2);
      exit (EXIT_FAILURE);
    }
  }
#else
  /* debug */
  verbose = 1;
#endif

  if (verbose)
  {
    timer = time (NULL);
    tblock = localtime (&timer);
    fprintf (verboseServerOutput, "%s Start: %s\n", argv[0], asctime (tblock));
    /* fprintf (verboseServerOutput, "Start: %s\n", asctime (tblock));  */
  }

  retCode = runServer(verbose, verboseServerOutput, errorServerOutput);
#ifndef DEBUG
  if (logFileTarget)
    fclose(logFileTarget);
  if (debugTarget)
    fclose(debugTarget);
#endif
  return retCode;
}
